DROP TABLE IF EXISTS t1;
DROP TABLE IF EXISTS t2;

CREATE TABLE t1 (a Int32) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE t2 (a UInt32, key UInt32) ENGINE = MergeTree ORDER BY tuple();

INSERT INTO t1 VALUES (1);
INSERT INTO t2 VALUES (2, 2);

SET join_use_nulls = 1;
SET enable_analyzer = 1;

-- { echoOn }

{% for KIND in ('LEFT', 'RIGHT', 'FULL') -%}

SELECT '============ {{ KIND }} JOIN ============' FORMAT Null;

{% for right_column_name in ['a', 'key'] -%}

SELECT a, toTypeName(a)
FROM (
    SELECT *
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    ON t1.a = t2.{{ right_column_name }}
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT a
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    ON t1.a = t2.{{ right_column_name }}
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT *
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    ON t1.a = t2.{{ right_column_name }}
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT t1.*
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    ON t1.a = t2.{{ right_column_name }}
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT t2.*
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    ON t1.a = t2.{{ right_column_name }}
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT t2.*
    FROM t1
    {{ KIND }} JOIN t2
    ON t1.a = t2.{{ right_column_name }}
) ORDER BY 1;

{% if right_column_name == 'a' -%}

SELECT *, * APPLY toTypeName
FROM (
    SELECT a
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    USING (a)
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT *
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    USING (a)
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT t1.*
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    USING (a)
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT t2.*
    FROM (SELECT 1 :: Int32 as a) t1
    {{ KIND }} JOIN (SELECT 2 :: UInt32 as {{ right_column_name }}) t2
    USING (a)
) ORDER BY 1;

SELECT *, * APPLY toTypeName
FROM (
    SELECT *
    FROM t1
    {{ KIND }} JOIN t2
    USING (a)
) ORDER BY 1;

{% endif -%}

{% endfor -%}
{% endfor -%}

-- { echoOff }

DROP TABLE IF EXISTS t1;
DROP TABLE IF EXISTS t2;
